<template>
  <div class="robots-container">
    <a-tabs v-model:activeKey="activeTab">
      <!-- 机器码管理 -->
      <a-tab-pane key="codes" tab="机器码管理">
        <div class="table-operations">
          <a-space>
            <a-button type="primary" @click="showCreateCodeModal">
              <plus-outlined /> 生成机器码
            </a-button>
            <a-input-search
              v-model:value="searchKeyword"
              placeholder="搜索机器码"
              style="width: 200px"
              @search="handleSearch"
            />
          </a-space>
        </div>

        <a-table
          :columns="codeColumns"
          :data-source="robotCodes"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #status="{ text }">
            <a-tag :color="getStatusColor(text)">
              {{ getStatusText(text) }}
            </a-tag>
          </template>

          <template #action="{ record }">
            <a-space>
              <a @click="showEditCodeModal(record)">编��</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除此机器码吗？"
                @confirm="handleDeleteCode(record)"
              >
                <a class="danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table>

        <!-- 机器码表单弹窗 -->
        <a-modal
          :title="modalTitle"
          :visible="modalVisible"
          :confirm-loading="modalLoading"
          @ok="handleModalOk"
          @cancel="handleModalCancel"
        >
          <a-form
            ref="formRef"
            :model="formState"
            :rules="rules"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <template v-if="!formState.id">
              <a-form-item label="生成数量" name="count">
                <a-input-number
                  v-model:value="formState.count"
                  :min="1"
                  :max="100"
                  style="width: 100%"
                />
              </a-form-item>
            </template>

            <a-form-item label="有效期(天)" name="expireDays">
              <a-input-number
                v-model:value="formState.expireDays"
                :min="1"
                :max="3650"
                style="width: 100%"
              />
            </a-form-item>

            <a-form-item label="状态" name="status">
              <a-switch
                v-model:checked="formState.status"
                :checked-value="1"
                :unchecked-value="0"
              />
            </a-form-item>
          </a-form>
        </a-modal>
      </a-tab-pane>

      <!-- 机器人配置 -->
      <a-tab-pane key="config" tab="机器人配置">
        <div class="config-container">
          <a-alert
            v-if="!selectedRobotId"
            message="请先选择一个机器人"
            type="info"
            show-icon
            style="margin-bottom: 16px"
          />
          <template v-else>
            <a-form
              ref="configFormRef"
              :model="configForm"
              :label-col="{ span: 4 }"
              :wrapper-col="{ span: 16 }"
            >
              <a-form-item label="机器人">
                <a-select
                  v-model:value="selectedRobotId"
                  style="width: 200px"
                  @change="handleRobotChange"
                >
                  <a-select-option
                    v-for="code in robotCodes"
                    :key="code.robotId"
                    :value="code.robotId"
                  >
                    {{ code.robotId }}
                  </a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item label="回复策略" name="replyAll">
                <a-radio-group v-model:value="configForm.replyAll">
                  <a-radio :value="-1">只读消息</a-radio>
                  <a-radio :value="0">仅私聊和@</a-radio>
                  <a-radio :value="1">全部回复</a-radio>
                </a-radio-group>
              </a-form-item>

              <a-form-item label="问答类型" name="qaType">
                <a-select v-model:value="configForm.qaType">
                  <a-select-option :value="0">不启用</a-select-option>
                  <a-select-option :value="1">ChatGPT</a-select-option>
                  <a-select-option :value="2">自定义API</a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item
                v-if="configForm.qaType === 2"
                label="回调地址"
                name="callbackUrl"
              >
                <a-input
                  v-model:value="configForm.callbackUrl"
                  placeholder="请输入回调地址"
                />
              </a-form-item>

              <a-form-item :wrapper-col="{ offset: 4 }">
                <a-button
                  type="primary"
                  :loading="configLoading"
                  @click="handleSaveConfig"
                >
                  保存配置
                </a-button>
              </a-form-item>
            </a-form>
          </template>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import {
  getRobots,
  getRobotConfig,
  updateRobotConfig,
  getRobotCodes,
  createRobotCodes,
  updateRobotCode,
  deleteRobotCode
} from '@/api/robot'

// 标签页相关
const activeTab = ref('codes')

// 机器码列表相关
const searchKeyword = ref('')
const loading = ref(false)
const robotCodes = ref([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: total => `共 ${total} 条`
})

const codeColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '机器码',
    dataIndex: 'robotId'
  },
  {
    title: '状态',
    dataIndex: 'status',
    slots: { customRender: 'status' }
  },
  {
    title: '过期时间',
    dataIndex: 'expireTime'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    slots: { customRender: 'action' }
  }
]

// 状态相关
const getStatusColor = (status) => {
  switch (status) {
    case 1: return 'success'
    case 0: return 'error'
    default: return 'default'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 1: return '正常'
    case 0: return '禁用'
    default: return '未知'
  }
}

// 表单相关
const formRef = ref()
const modalVisible = ref(false)
const modalLoading = ref(false)
const modalTitle = ref('')
const formState = reactive({
  id: '',
  count: 1,
  expireDays: 365,
  status: 1
})

const rules = {
  count: [
    { required: true, message: '请输入生成数量' }
  ],
  expireDays: [
    { required: true, message: '请输入有效期' }
  ]
}

// 配置相关
const configFormRef = ref()
const configLoading = ref(false)
const selectedRobotId = ref('')
const configForm = reactive({
  replyAll: 0,
  qaType: 0,
  callbackUrl: ''
})

// 获取机器码列表
const fetchRobotCodes = async () => {
  loading.value = true
  try {
    const { data } = await getRobotCodes({
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchKeyword.value
    })
    robotCodes.value = data.list
    pagination.total = data.total
  } catch (error) {
    console.error('获取机器码列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取机器人配置
const fetchRobotConfig = async () => {
  if (!selectedRobotId.value) return
  
  configLoading.value = true
  try {
    const { data } = await getRobotConfig(selectedRobotId.value)
    Object.assign(configForm, data)
  } catch (error) {
    console.error('获取机器人配置失败:', error)
  } finally {
    configLoading.value = false
  }
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchRobotCodes()
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchRobotCodes()
}

// 显示创建机器码弹窗
const showCreateCodeModal = () => {
  modalTitle.value = '生成机器码'
  Object.assign(formState, {
    id: '',
    count: 1,
    expireDays: 365,
    status: 1
  })
  modalVisible.value = true
}

// 显示编辑机器码弹窗
const showEditCodeModal = (record) => {
  modalTitle.value = '编辑机器码'
  Object.assign(formState, {
    id: record.id,
    expireDays: 365,
    status: record.status
  })
  modalVisible.value = true
}

// 弹窗确认
const handleModalOk = () => {
  formRef.value.validate().then(async () => {
    modalLoading.value = true
    try {
      if (formState.id) {
        await updateRobotCode(formState)
        message.success('更新成功')
      } else {
        await createRobotCodes(formState)
        message.success('生成成功')
      }
      modalVisible.value = false
      fetchRobotCodes()
    } catch (error) {
      console.error('操作失败:', error)
    } finally {
      modalLoading.value = false
    }
  })
}

// 弹窗取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value.resetFields()
}

// 删除机器码
const handleDeleteCode = async (record) => {
  try {
    await deleteRobotCode(record.id)
    message.success('删除成功')
    if (robotCodes.value.length === 1 && pagination.current > 1) {
      pagination.current--
    }
    fetchRobotCodes()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 机器人切换
const handleRobotChange = () => {
  fetchRobotConfig()
}

// 保存配置
const handleSaveConfig = async () => {
  if (!selectedRobotId.value) {
    message.warning('请先选择机器人')
    return
  }

  configLoading.value = true
  try {
    await updateRobotConfig({
      robotId: selectedRobotId.value,
      ...configForm
    })
    message.success('保存成功')
  } catch (error) {
    console.error('保存配置失败:', error)
  } finally {
    configLoading.value = false
  }
}

onMounted(() => {
  fetchRobotCodes()
})
</script>

<style scoped>
.robots-container {
  padding: 24px;
  background: #fff;
}

.table-operations {
  margin-bottom: 16px;
}

.config-container {
  padding: 24px;
  background: #fafafa;
  border-radius: 2px;
}

.danger {
  color: #ff4d4f;
}

.danger:hover {
  color: #ff7875;
}
</style> 